import threading
import asyncio
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from agents.agent import langgraph_mcp_agent

app = FastAPI()
graph = None


class UserInputRequest(BaseModel):
    user_input: str



@app.post("/chat")
async def chat(request: UserInputRequest):
    if not graph:
        raise HTTPException(status_code=500, detail="Graph not initialized")

    user_input = request.user_input
    if user_input.lower() in ["quit", "exit", "q"]:
        return {"response": "Goodbye!"}

    current_thread_id = threading.current_thread().ident
    config = {"configurable": {"thread_id": str(current_thread_id)}}

    response_content = []
    async for event in graph.astream(
        {"messages": [{"role": "user", "content": user_input}]},
        config,
        stream_mode="messages"
    ):
        print("api:", event)
        # lastest_message = event["messages"][-1]
        # if lastest_message.type == "ai":
        #     response_content.append(lastest_message.content)

    return response_content

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=5050)
